package com.qiwx.pigeon.activity.manager;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.fragment.app.FragmentTransaction;
import androidx.viewpager.widget.ViewPager;

import com.google.android.material.tabs.TabLayout;
import com.qiwx.pigeon.R;
import com.qiwx.pigeon.Utils.MyToast;
import com.qiwx.pigeon.Utils.NumberUtil;
import com.qiwx.pigeon.adapter.query.TabPagerAdapter;
import com.qiwx.pigeon.base.BaseActivity;
import com.qiwx.pigeon.data.CageStatusConfig;
import com.qiwx.pigeon.data.db.CageModel;
import com.qiwx.pigeon.data.vo.QueryCageBean;
import com.qiwx.pigeon.fragment.manager.CagemanagerFragment;
import com.qiwx.pigeon.widget.AmountView;
import com.qiwx.pigeon.widget.ArrowView;

import org.litepal.LitePal;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * @description
 * @Author qiwx
 * @Date 2020-03-25 10:40
 * 鸽笼管理
 **/
public class CageManagerActivity extends BaseActivity {
    @BindView(R.id.title_content)
    TextView titleContent;
    @BindView(R.id.title_return)
    ArrowView titleReturn;
    @BindView(R.id.edt_cage_number)
    EditText edtCageNumber;
    @BindView(R.id.btn_add)
    Button btnAdd;
    @BindView(R.id.txt_cage_all_count)
    TextView txtCageAllCount;
    @BindView(R.id.txt_cage_using_count)
    TextView txtCageUsingCount;
    @BindView(R.id.txt_cage_unusing_count)
    TextView txtCageUnusingCount;
    //    @BindView(R.id.sw_status)
//    TextView switchCompat;
    int wh_id;
    @BindView(R.id.llTitle)
    LinearLayout llTitle;
    @BindView(R.id.title_right)
    TextView titleRight;
    @BindView(R.id.tab_layout)
    TabLayout tabLayout;
    @BindView(R.id.viewPager)
    ViewPager viewPager;
    private int mIndex = -1;
    private boolean isCl = true;//存栏状态
    int clAmount;//存栏数
    int klAmount;//空笼数
    List<QueryCageBean> list = new ArrayList<>();
    TabPagerAdapter adapter;
    String[] titles;
    public List<Fragment> fragmentList = new ArrayList<>();


    @Override
    public int getLayoutId() {
        return R.layout.activity_cage_manager_layout;
    }

    LinkedList<CagemanagerFragment> fragmentStack = new LinkedList<>();

    @Override
    public void initAfterOnCreate() {
        wh_id = getIntent().getIntExtra("wh_id", 0);
        if (wh_id < 0) {
            MyToast.showLong("鸽仓编号有问题，请重新选择鸽仓");
            finish();
        }
        titleReturn.changeArrowLeft();
        titleContent.setText("鸽笼管理");
        titles = new String[]{"存栏", "空笼"};
        initFragment();
        initView();

    }

    private CagemanagerFragment getFragment(int status) {
        Bundle bundle = new Bundle();
        bundle.putInt("wh_id", wh_id);
        bundle.putInt("status", status);
        CagemanagerFragment fragment = new CagemanagerFragment();
        fragment.setArguments(bundle);
        return fragment;
    }

    private void initFragment() {
        fragmentList.clear();
        fragmentList.add(getFragment(1));
        fragmentList.add(getFragment(0));

//        FragmentManager fm = getSupportFragmentManager();
//        FragmentTransaction ft = fm.beginTransaction();
//        fragmentStack.add(getFragment(1));
//        ft.add(R.id.flContent, fragmentStack.peek());
//        ft.commitNow();
//        mIndex = -1;
    }

    private void initView() {
        adapter = new TabPagerAdapter(getSupportFragmentManager(), titles, fragmentList);
        viewPager.setAdapter(adapter);
        viewPager.setOffscreenPageLimit(4);
        tabLayout.setupWithViewPager(viewPager);
        tabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                //选中某个tab
                tab.getPosition();
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                //当tab从选择到未选择
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
                //已经选中tab后的重复点击tab
            }
        });

        edtCageNumber.setOnFocusChangeListener((v, hasFocus) -> {
            if (hasFocus) {
                edtCageNumber.setCursorVisible(true);
            } else {
                // 失去焦点
                edtCageNumber.setCursorVisible(false);
            }
        });
        edtCageNumber.setOnTouchListener((v, event) -> {
            edtCageNumber.setFocusable(true);
            edtCageNumber.setFocusableInTouchMode(true);
            return false;
        });
    }

    public void setAmount(int status, int amount) {
        if (status == CageStatusConfig.STATUS_KL) {
            klAmount = amount;
        } else {
            clAmount = amount;
        }
        txtCageUsingCount.setText(clAmount + "");
        txtCageUnusingCount.setText(klAmount + "");
        txtCageAllCount.setText((clAmount + klAmount) + "");
    }
    public void onUpdateAmount(){

    }

    //添加鸽笼
    private void addCages() {
//        CageParam cageParam = new CageParam();
//        cageParam.setAddCageAmount(amount);
//        cageParam.setWh_id(wh_id);
        CagemanagerFragment cf = getCrrentFragment();
        if (cf != null) {
            int amount = NumberUtil.parseInt(edtCageNumber.getText().toString());
            if (amount > 0) {
                cf.addCage(amount);
            } else {
                MyToast.showLong("鸽笼数必须大于0");
            }
        }


//        int startNum;
//        //查询起始id
//        CageModel model = LitePal.where("wh_id=?", String.valueOf(wh_id)).findLast(CageModel.class);
//        if (model == null) {
//            startNum = 1;
//        } else {
//            startNum = model.getNumber() + 1;
//        }
//        List<CageModel> list = new ArrayList<>();
//
//        for (int i = 0; i < amount; i++) {
//            CageModel cm = new CageModel();
//            cm.setWh_id(wh_id);
//            //存栏时间默认是当前时间7天前，为了补录日期日期限制
//            long current= DateTimeUtils.addDay(new Date(),-7).getTime();
//            cm.setCreate_date(current);
//            cm.setUpdate_date(current);
//            cm.setNumber(startNum++);
//            // cm.setGigeon_status(CageStatusConfig.STATUS_YGYM);//默认是一公一母
//            //默认存栏状态
//            cm.setStatus(CageStatusConfig.STATUS_YGYM);
//            cm.setProduce_status(CageStatusConfig.PRODUCE_KW);
//            cm.setKw_date(current);
//            cm.save();
//            list.add(cm);
//        }
//        WareHouseModel wareHouseModel = LitePal.find(WareHouseModel.class, wh_id);
//        if (wareHouseModel != null) {
//            wareHouseModel.setCages(list);
//            if (wareHouseModel.save()) {
//                MyToast.showShort("添加成功");
//                updateData();
//            }
//        }

    }

    private void updateData() {
        updateCount();
        for (int i = 0; i < fragmentStack.size(); i++) {
            fragmentStack.get(i).queryCount();
            fragmentStack.get(i).loadData();
        }
    }

    private void changeFragment(FragmentTransaction ft, CagemanagerFragment fragment) {
        if (fragmentStack.peek() != null) {
            ft.hide(fragmentStack.pop());
        }
        fragmentStack.push(fragment);
        ft.show(fragment);
    }

    @Nullable
    public CagemanagerFragment findFragment(String name) {
        return (CagemanagerFragment) getSupportFragmentManager().findFragmentByTag(name);
    }

    public void setIndexSelected(int index) {
        if (mIndex == index) {
            return;
        }
        FragmentManager fragmentManager = getSupportFragmentManager();
        FragmentTransaction ft = fragmentManager.beginTransaction();
        ft.setCustomAnimations(R.anim.fragment_enter, R.anim.fragment_exit);
        CagemanagerFragment usingFragment = findFragment("UsingFragment");
        CagemanagerFragment unusingFragment = findFragment("UnusingFragment");

        switch (index) {
            case 0:
                if (usingFragment == null) {
                    usingFragment = getFragment(1);
                    ft.add(R.id.flContent, usingFragment, "UsingFragment");
                }
                changeFragment(ft, usingFragment);
                break;
            case 1:
                if (unusingFragment == null) {
                    unusingFragment = getFragment(0);
                    ft.add(R.id.flContent, unusingFragment, "UnusingFragment");
                }
                changeFragment(ft, unusingFragment);
                break;
        }
        ft.commit();
        mIndex = index;
    }

    @OnClick({R.id.btn_add, R.id.title_return})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_add:
                addCages();
                break;
            case R.id.title_return:
                finish();
                break;
        }
    }

    public void updateCount() {
        int usingCount = 0;//存栏数
        int sum = 0;//总数
        sum = LitePal.where("wh_id=?", wh_id + "").count(CageModel.class);

        usingCount = LitePal.where("wh_id=? and status=?", wh_id + "", "1").count(CageModel.class);
//        Cursor cursor = LitePal.findBySQL("select count(*) as count from wh_id");
//        if (cursor != null) {
//            while (cursor.moveToNext()) {
//                int index = cursor.getColumnIndex("count");
//                if (index >= 0) {
//                    sum = cursor.getInt(0);
//                }
//            }
////            cursor.close();
//        }

//        cursor = LitePal.findBySQL("select count(*) as count from wh_id where status =1");
//        if (cursor != null) {
//            while (cursor.moveToNext()) {
//                int index = cursor.getColumnIndex("count");
//                if (index >= 0) {
//                    usingCount = cursor.getInt(0);
//                }
//            }
//        }
//        if (cursor != null) {
//            cursor.close();
//        }
        txtCageAllCount.setText(sum + "");
        txtCageUsingCount.setText(usingCount + "");
        txtCageUnusingCount.setText(sum - usingCount + "");
    }

    //获取当前fragment
    private CagemanagerFragment getCrrentFragment() {
        FragmentManager fragmentManager = getSupportFragmentManager();
        List<Fragment> fragments = fragmentManager.getFragments();
        for (Fragment fragment : fragments) {
            if (fragment != null && fragment.isVisible())
                return (CagemanagerFragment) fragment;
        }
        return null;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }
}
